// D3DDeviceDrvTexture2D.cpp (c) 2011 JV Software
//

#include "D3DDeviceDrvPrivate.h"

//
// InitFromBuffer
// 
void D3DTexture2D::InitFromBuffer( FTextureHeader_t *header) {
	D3D11_SUBRESOURCE_DATA textureData;

	// Create depth stencil texture
    ZeroMemory( &descTex, sizeof(descTex) );
    descTex.Width = header->width;
    descTex.Height = header->height;
    descTex.MipLevels = 1;
    descTex.ArraySize = 1;
    descTex.SampleDesc.Count = 1;
    descTex.SampleDesc.Quality = 0;
    descTex.Usage = D3D11_USAGE_DEFAULT;
    descTex.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    descTex.CPUAccessFlags = 0;
    descTex.MiscFlags = 0;

	textureData.pSysMem = ((byte *)header + sizeof(FTextureHeader_t));
	textureData.SysMemSlicePitch = 0;

	switch(header->format) {
		case TEX_FORMAT_RGBA:
			descTex.Format = DXGI_FORMAT_R8G8B8A8_UINT;
			textureData.SysMemPitch = header->width * 4;
		break;

		case TEX_FORMAT_DXT1:
			descTex.Format = DXGI_FORMAT_BC1_UNORM;
			textureData.SysMemPitch = ((header->width + 3) >> 2) * 4;
		break;

		case TEX_FORMAT_DXT3:
			descTex.Format = DXGI_FORMAT_BC2_UNORM;
			textureData.SysMemPitch = ((header->width + 3) >> 2) * 4;
		break;

		case TEX_FORMAT_DXT5:
			descTex.Format = DXGI_FORMAT_BC3_UNORM;
			textureData.SysMemPitch = ((header->width + 3) >> 2) * 4;
		break;

		default:
			engine->FatalError( TEXT("InitTexture2D: Unsupported format") );
		break;
	}

	if(FAILED(d3dDevice.Device()->CreateTexture2D( &descTex, &textureData, &texture2D ))) {
		engine->FatalError( TEXT("CreateTexture2D failed...\n" ));
	}

	if(FAILED(d3dDevice.Device()->CreateShaderResourceView( texture2D, NULL, &textureResourceView ))) {
		engine->FatalError( TEXT("CreateShaderResourceView: failed\n" ));
	}
}

//
// InitAsDepthStencilTexture
// 
void D3DTexture2D::InitAsDepthStencilTexture( int width, int height ) {
	HRESULT		hr;

	// Create depth stencil texture
    ZeroMemory( &descTex, sizeof(descTex) );
    descTex.Width = width;
    descTex.Height = height;
    descTex.MipLevels = 1;
    descTex.ArraySize = 1;
    descTex.SampleDesc.Count = 1;
    descTex.SampleDesc.Quality = 0;
    descTex.Usage = D3D11_USAGE_DEFAULT;
    descTex.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    descTex.CPUAccessFlags = 0;
    descTex.MiscFlags = 0;
	descTex.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;

	

    hr = d3dDevice.Device()->CreateTexture2D( &descTex, NULL, &texture2D );
	if( FAILED( hr ) ) {
		engine->FatalError( TEXT("Create depth stencil texture failed...\n" ));
	}

	_name = TEXT("_depthStencil");
}

//
// Destroy
// 
void D3DTexture2D::Destroy( void ) {
	texture2D->Release();
}